package ch.sv7.tool.dbmanager.integration.sybase;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.DriverManager;

import ch.sv7.tool.dbmanager.types.TypeInfo;
import ch.sv7.tool.dbmanager.types.TypesInfo;
import ch.sv7.tool.dbmanager.types.TypesInfoFactory;

/**
 * TODO: Document me!
 *
 * @author svt
 *
 */
public class ConnectionFactory {

	public static final String NL = "\n";
	
	public static Connection getTestConnection() throws Exception {
		Class.forName("com.sybase.jdbc3.jdbc.SybDriver");
		Connection conn = DriverManager.getConnection(
				"jdbc:sybase:Tds:w7224:6000/test", 
				"test",
				"testtest");
		if (conn == null) {
			throw new RuntimeException("Unable to obtain connection");
		}
		return conn;		
	}
	
	public static void main(String[] args) throws Exception {
		TypesInfo ti = TypesInfoFactory.getInstance().getTypesInfo("sybase", getTestConnection());
		String[] typesNames = ti.getTypeNames();
		for (int i=0; i<typesNames.length; i++) {
			String typeName = typesNames[i];
			TypeInfo type = ti.getTypeInfo(typeName);
			dump(typeName, type);
			
		}
	}
	
	public static void dump(String type, Object object) throws Exception {
		Field[] fields = object.getClass().getDeclaredFields();
		StringBuffer buffer = new StringBuffer();
		String className = object.getClass().getName();
		className = className.substring(className.lastIndexOf(".") + 1);
		buffer.append("types.put(\"" + type + "\", new " + className + "(" + NL);
		for (int i=0; i<fields.length; i++) {
			Field f = fields[i];
			boolean isString = f.getType().equals(String.class);
			boolean isShort = f.getType().equals(short.class);
			f.setAccessible(true);
			Object value = f.get(object);
			buffer.append("\t");
			if (isString && value != null){
				buffer.append("\"");
			}
			if (isShort){
				buffer.append("(short)");
			}
			buffer.append(value);
			if (isString && value != null){
				buffer.append("\"");
			}
			buffer.append("/*" + f.getName() + "*/");
			if (i<fields.length - 1) {
				buffer.append(", ");
			}
			buffer.append(NL);
		}
		buffer.append("));");
		System.out.println(buffer.toString());
	}
}
